package com.pactera.integral.security.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pactera.integral.common.web.WebResponse;
import com.pactera.integral.security.authentication.TokenAuthenticationService;
import org.springframework.util.DigestUtils;

/**
 * @author shilei
 * @Date 2017/6/9.
 */
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    public JWTLoginFilter(String url, AuthenticationManager authManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException,
            IOException, ServletException {
    	ObjectMapper mapper = new ObjectMapper();
    	JsonNode user = mapper.readTree(req.getInputStream());
        String nameString = user.get("username").asText();
        String pwdString = user.get("password").asText();
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(nameString, DigestUtils.md5DigestAsHex(pwdString.getBytes())));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth)
            throws IOException, ServletException {
        TokenAuthenticationService.addAuthentication(response, auth.getName());
        //build return token message.
        ObjectMapper mapper = new ObjectMapper();
        WebResponse res = new WebResponse();
        res.setResponseCode("0");
        HashMap<String,String> tokenInfo = new HashMap<String,String>();
        tokenInfo.put("authorization", response.getHeader("Authorization"));
        tokenInfo.put("username", auth.getName());
        res.setData(tokenInfo);
        String jsonString = mapper.writeValueAsString(res);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.flush();
    }
}
